from flask import Flask, request
from sqlalchemy import create_engine
# from flask_cors import CORS
import requests
import json
import time
import yaml
import logging

# 这个文件是为了避免循环依赖
config = yaml.load(open("./config.yaml", "r", encoding="utf-8"), Loader=yaml.FullLoader)
logcfg = config["log"]
sqlcfg = config["mysql"]
dsn = f'{sqlcfg["driver"]}://{sqlcfg["username"]}:{sqlcfg["password"]}@{sqlcfg["host"]}:{sqlcfg["port"]}/{sqlcfg["dbname"]}?charset=utf8&parseTime=True&loc=Local'
logger = logging.getLogger()
# db = create_engine(dsn)
db = 1
app = Flask(__name__)


# CORS(app)
def add_router(url, method):
    req = {
        "FromURL": url,
        "Method": method,
        "ToHost": request.host,
        "Weight": 10,
        "VerfiyLevel": 0xff
    }
    headers = {
        "Content-Type": "application/json"
    }
    data = json.dumps(req)

    while True:
        response = requests.post(config["gatWayHost"] + "/inner/addrouter", headers=headers, data=data)
        if response.status_code == 200:
            break
        else:
            logger.error("Add router error, status: %d", response.status_code)
            time.sleep(10)


def init_routers():
    routes = app.url_map.iter_rules()
    for route in routes:
        url = route.rule
        for methods in route.methods:
            add_router(url, methods)
    logger.info("Add router success")


def init_logger():
    args = {
        "level": "",
        "filename": f"{logcfg['filename']}",
        "format": "time=%(asctime)s level=%(levelname)s msg=%(message)s func%(funcName)s file=%(filename)s"
    }
    match logcfg["level"]:
        case "debug":
            args["level"] = logging.DEBUG
        case "info":
            args["level"] = logging.INFO
        case "warning":
            args["level"] = logging.WARNING
        case "error":
            args["level"] = logging.ERROR
        case _:
            print("log level error")
    logging.basicConfig(**args)
